package me.zingon.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.zingon.dao.MaterialsDao;
import me.zingon.model.Material;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;

@Service
public class MaterialsService {

    @Autowired
    MaterialsDao materialsDao;

    @Autowired
    Properties msg;

    public int save(Material m,MultipartFile[] materials) throws IOException {
        String location="";
        for(MultipartFile file:materials){
            if(file.getSize()>0) {
                File f = new File(getDirectory() + File.separator + file.getOriginalFilename().split("\\.")[0] + new Date().getTime() + "." + file.getOriginalFilename().split("\\.")[1]);
                file.transferTo(f);
                location+=f.getPath()+",";
            }
        }
        if(location.length()>0)
            m.setLocation(location.substring(0,location.length()-1));
        m.setXq(HtmlUtils.htmlEscape(m.getXq()));
        m.setSubject(HtmlUtils.htmlEscape(m.getSubject()));
        m.setTeacher(HtmlUtils.htmlEscape(m.getTeacher()));
        m.setDescribe(HtmlUtils.htmlEscape(m.getDescribe()));
        materialsDao.saveMaterial(m);
        return m.getId();
    }

    public PageInfo<Material> getMaterialWithSth(String xq,String subject,String teacher,int offline,int star,int pageNumber,int pageSize){
        PageHelper.startPage(pageNumber,pageSize);
        List<Material> materials=materialsDao.getMaterialWithSth(xq,subject,teacher,offline,star);
        PageInfo<Material> pageInfo=new PageInfo<Material>(materials);
        return pageInfo;
    }

    public String getDirectory() throws IOException {
        Date date=new Date();
        Calendar c=Calendar.getInstance();
        c.setTime(date);
        File dir=new File(msg.getProperty("path")+File.separator+"uploads"+File.separator
                            +c.get(Calendar.YEAR)+File.separator
                            +c.get(Calendar.MONTH)+File.separator
                            +c.get(Calendar.DATE));
        if(!dir.exists())
            dir.mkdirs();
        return dir.getAbsolutePath();
    }
}
